package rewardsonline.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;

import rewardsonline.interceptor.FragmentRequestHandlingInterceptor;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

	@Override
    public Validator getValidator() {
        return new LocalValidatorFactoryBean();
    }
	
	/**
	 * Define controllers which only render pages (i.e. nothing added to the 
	 * model)
	 */
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("welcome");
		registry.addViewController("/home").setViewName("welcome");
	}
	
	/**
	 * Interceptor to set caching response headers. Applied to all handler 
	 * mappings.
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new FragmentRequestHandlingInterceptor());
	}
	
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		// Resolves view names to Tiles definitions
		registry.tiles();
	}
	
	@Bean
	@Description("Configures Tiles")
	TilesConfigurer tilesConfigurer() {
		TilesConfigurer tilesConfigurer = new TilesConfigurer();
		tilesConfigurer.setDefinitions("/WEB-INF/tiles.xml");
		return tilesConfigurer;
	}
}
